package org.sunnyleaf.votedemo.client.ui;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.*;

import org.sunnyleaf.votedemo.client.GreetingServiceAsync;
import org.sunnyleaf.votedemo.client.GreetingServiceAsyncFactory;
import org.sunnyleaf.votedemo.client.Votedemo;
import org.sunnyleaf.votedemo.client.data.*;

import java.util.List;
import java.util.Vector;
public class VotePage extends Composite {
	
	private Vote vote;
	private VoteRecord record;
	private Vector<Vector<Integer>> selectInfo = new Vector< Vector<Integer> >();
	private List<VoteItem> voteItemArray;
	private Votedemo mainPage;
	
	public void setMainPanle( Votedemo mainpage ){
		this.mainPage = mainpage;
	}
	
	public VotePage( Vote v, VoteRecord r ){
		this.vote = v;
		this.record = r;
		VerticalPanel mainVp = new VerticalPanel();
		mainVp.add( new HTML("标题:" + v.getVoteName() ) );
		int index = 0;

		selectInfo.setSize( v.getVoteItems().size());
		
		for( VoteItem item: v.getVoteItems()){
			mainVp.add(new VoteItemOption(index++,item));
		}
		
		Button commitButton =  new Button("提交", new ClickHandler(){
			@Override
			public void onClick(ClickEvent event) {
				// 更新投票的数据
				GreetingServiceAsync gsa = GreetingServiceAsyncFactory.getServiceInstance();
				vote.setVotedCount(vote.getVotedCount()+1);
				record.setVoted(true);
				gsa.saveVoteRecord( record, new AsyncCallback<String>(){
					@Override
					public void onFailure(Throwable caught) {
						Window.alert("保存VoteRecord失败");
					}

					@Override
					public void onSuccess(String result) {
						GWT.log("更新VoteRecord成功", null);
					}
				});
				// 更新完VoteItems后才能更新Vote
				updateVoteItems();			
			}
		});
	
		mainVp.add( commitButton );
		mainVp.setSpacing(15);
		mainVp.setCellHorizontalAlignment( commitButton, mainVp.ALIGN_RIGHT );
		
		this.initWidget(mainVp);
	}
	
	public void updateVoteItems(){
		GreetingServiceAsync gsa = GreetingServiceAsyncFactory.getServiceInstance();
		// update voted items in this vote page
		// 需要重新查询所有VoteItems，更新数据，避免写入冲突
		gsa.getVoteItems(vote.getId(), new AsyncCallback<List<VoteItem>>(){
			@Override
			public void onFailure(Throwable caught) {
				Window.alert("更新VoteItem数据失败");
			}

			@Override
			public void onSuccess(List<VoteItem> result) {
				voteItemArray = result;
				int questionId = 0;
				for( VoteItem item:voteItemArray ){
					// 增加投票人数
					item.incPolled();
					for( Integer select : selectInfo.get(questionId)){
						// 增加选择该选项的人数
						item.incItemCount( select );
					}			
					questionId++;
				}
				vote.setVoteItems(voteItemArray);
				
				GreetingServiceAsyncFactory.getServiceInstance().saveVote( vote , new AsyncCallback<String>(){

					@Override
					public void onFailure(Throwable caught) {
						Window.alert("投票数据保存失败");
					}

					@Override
					public void onSuccess(String result) {
						Window.alert("投票提交成功");
						deleteSelf();
						// 必须更新User页面
						// 若这个投票是投票者发起的，需要更新Owner页面
						mainPage.updateAttendVotePanel( vote, Votedemo.UPDATE_TYPE.UPDATE, true );
						if( vote.getOwner().equals( Votedemo.getEmail() ))
							mainPage.updateSponseredVotePanel();	
					}
				});
			}
		});		
	}
	
	// 删除自身界面
	private void deleteSelf(){
		Panel parent = (Panel)this.getParent();
		parent.remove(this);
	}
	
	class VoteItemOption extends Composite {
	
		private int instanceId;

		private class SelectionHandler implements ValueChangeHandler<Boolean>{
				
			private int index;			// 选项序号
			private boolean bSingle;	// 是否是单选
			Vector<Integer> selectionInfo;
			
			SelectionHandler( boolean single, int index, Vector<Integer> seleInfo ){
				this.index = index;
				this.selectionInfo = seleInfo;
				this.bSingle = single;
			}
			
			@Override
			public void onValueChange(ValueChangeEvent<Boolean> event) {
				if( bSingle ){
					if( (Boolean)event.getValue() == true )
						this.selectionInfo.clear();
						this.selectionInfo.add(this.index);
				}
				else {
					if( (Boolean)event.getValue() == true ){
						selectionInfo.add(index);
					}else {
						selectionInfo.removeElement(index);
					}
				}	
			}
		}
			
		public VoteItemOption( int index,  VoteItem item ) {
			this.instanceId = index;
			VerticalPanel vp = new VerticalPanel();
			vp.setWidth("100%");
			int selectionIndex = 0;
			vp.add( new Label("问题"+(index+1)+": "+item.getQuestion()));
			vp.setStyleName("voteopinion-border");
			
			for( String itemName : item.getItemArray()){	
				if( item.getType().equals( VoteItem.SINGLE )){
					RadioButton radio = new RadioButton("selection"+instanceId, itemName );
					if( selectInfo.get(instanceId) == null ){
						selectInfo.set(instanceId, new Vector<Integer>());
					}
					
					radio.setTitle( String.valueOf( selectionIndex ));
					vp.add( radio );
					radio.addValueChangeHandler(new SelectionHandler( true, selectionIndex,selectInfo.get(instanceId)));
				}
				
				else {
					CheckBox check = new CheckBox( itemName );
					if( selectInfo.get(instanceId) == null ){
						selectInfo.set(instanceId, new Vector<Integer>());
					}
					vp.add( check );
					check.addValueChangeHandler( new SelectionHandler( false, selectionIndex, selectInfo.get(instanceId)));				
				}
				selectionIndex++;
			}

			initWidget(vp);
		}
	}
}
